//
//  APOIVLELogin.m
//  Apallo
//
//  Created by Jason Poh on 19/8/14.
//  Copyright (c) 2014 Apallo. All rights reserved.
//

#import "APOIVLELogin.h"
#import "APOConstants.h"

@interface APOIVLELogin()

//private instance variable
@property (strong, nonatomic) NSMutableData *receivedData;
@property (strong, nonatomic) NSMutableURLRequest *request;
//private methods
-(NSString*)clean_matric_no: (NSString*)matric_no;

@end

@implementation APOIVLELogin

//constants
NSString *const IVLE_LOGIN_NOTIFICATION = @"IVLE_LOGIN_NOTIFICATION";
NSString *const IVLE_TOKEN = @"IVLE_TOKEN";

-(NSString*) clean_matric_no: (NSString*)matric_no
{
    //TO-DO
     NSLog(@"Cleaning matric_no: ");
    return matric_no;
}

-(void)login: (NSString*)matric_no :(NSString*)password
{
    NSLog(@"Logging in to IVLE: ");
    //Clean matric number
    matric_no = [self clean_matric_no:matric_no];
    
    // Create the request.
    NSString *url_str = [NSString stringWithFormat:@"https://ivle.nus.edu.sg/api/login/?apikey=%@", API_KEY];
    
    _request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url_str]
                                                        cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                        timeoutInterval:60.0];
    
    //Init receivedData
    _receivedData = [NSMutableData dataWithCapacity:0];
    
    NSString *stringData = [NSString stringWithFormat:@"userid=%@&password=%@&__VIEWSTATE=/wEPDwULLTEzODMyMDQxNjEPFgIeE1ZhbGlkYXRlUmVxdWVzdE1vZGUCARYCAgEPZBYEAgEPD2QWAh4Gb25ibHVyBQ91c2VySWRUb1VwcGVyKClkAgkPD2QWBB4Lb25tb3VzZW92ZXIFNWRvY3VtZW50LmdldEVsZW1lbnRCeUlkKCdsb2dpbmltZzEnKS5zcmM9b2ZmaW1nLnNyYzE7Hgpvbm1vdXNlb3V0BTRkb2N1bWVudC5nZXRFbGVtZW50QnlJZCgnbG9naW5pbWcxJykuc3JjPW9uaW1nLnNyYzE7ZBgBBR5fX0NvbnRyb2xzUmVxdWlyZVBvc3RCYWNrS2V5X18WAQUJbG9naW5pbWcx",matric_no,password];
    
    // Set the request's content type to application/x-www-form-urlencoded
    [_request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    // Designate the request a POST request and specify its body data
    [_request setHTTPMethod:@"POST"];
    [_request setHTTPBody:[NSData dataWithBytes:[stringData UTF8String] length:strlen([stringData UTF8String])]];
    
    
    // Create url connection and fire request
    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:_request delegate:self startImmediately:YES];
    NSLog(@"connection: %@", [conn debugDescription]);
    //Connection failed
    if(!conn){
        NSLog(@"IVLE_LOGIN: Connection failed");
    }else {
        NSLog(@"IVLE_LOGIN: Connection succeeded");
    }
    
   // return YES;
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse: (NSURLResponse *)response
{
    // This method is called when the server has determined that it
    // has enough information to create the NSURLResponse object.
    
    // It can be called multiple times, for example in the case of a
    // redirect, so each time we reset the data.
    
    // receivedData is an instance variable declared elsewhere.
    [_receivedData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData: (NSData *)data
{
    // Append the new data to receivedData.
    // receivedData is an instance variable declared elsewhere.
    [_receivedData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError: (NSError *)error
{
    // Release the connection and the data object
    // by setting the properties (declared elsewhere)
    // to nil.  Note that a real-world app usually
    // requires the delegate to manage more than one
    // connection at a time, so these lines would
    // typically be replaced by code to iterate through
    // whatever data structures you are using.
    _receivedData = nil;
    
    // inform the user
    NSLog(@"Connection failed! Error - %@ %@",
          [error localizedDescription],
          [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}


- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    // do something with the data
    // receivedData is declared as a property elsewhere
    NSLog(@"Succeeded! Received %d bytes of data",[_receivedData length]);
    NSString* responseString = [[NSString alloc] initWithData:_receivedData encoding:NSUTF8StringEncoding];
    if(_receivedData.length == 416){
        NSLog(@"Token: %@", responseString);
        [self postNotificationWithString:responseString];
    } else {
        NSLog(@"Failed to get IVLE Token: %@", responseString);
        [self postNotificationWithString:@"FAILED"];
    }
    
    // Release the connection and the data object
    // by setting the properties (declared elsewhere)
    // to nil.  Note that a real-world app usually
    // requires the delegate to manage more than one
    // connection at a time, so these lines would
    // typically be replaced by code to iterate through
    // whatever data structures you are using.
    _receivedData = nil;
}

- (void)postNotificationWithString:(NSString *)data //post notification method and logic
{
    NSDictionary *dictionary = [NSDictionary dictionaryWithObject:data forKey:IVLE_TOKEN];
    [[NSNotificationCenter defaultCenter] postNotificationName:IVLE_LOGIN_NOTIFICATION object:nil userInfo:dictionary];
}
@end
